/*
 * uart_slave.c
 *
 *  Created on: May 23, 2025
 *      Author: lsy18
 */

#include "uart_slave.h"
#include "Uart_slave_REG/uart_slave_reg.h"

#include "../Communicate/Xor/xor.h"
#include "../Communicate/Uart_com/uart_it.h"
#include "../Hardware/Motor/motor.h"
#include "../Hardware/Pos/pos.h"

#include "../Hardware/Led/led.h"

uint8_t time_num = 0x00;

uint8_t tran_buff[256];
//const uint8_t tran_head = 0xAA;

void uart_slave_init()
{
	uart_slave_reg_init();
	slave_uart.receive_num = 0;
	slave_uart.buff_num = 0x09;
	HAL_UART_Receive_IT(&huart_slave_it, &slave_uart.uart_bit_buff, 1);
	HAL_TIM_Base_Start_IT(&htim_slave_send);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim == &htim_slave_send)
	{
		//HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
		if(reg_array[MODE_REG] == time_mode)
		{
			if(time_num >= reg_array[TIME_INT_REG])
			{
				tran_buff[0] = TRAN_HEAD;
				tran_buff[1] = SLAVE_ADRESS;
				tran_buff[2] = 0x00 | reg_array[REGISTER_STAR_REG];
				tran_buff[3] = reg_array[REGISTER_NUM_REG];
				time_num = 0;
				uart_slave_reg_read(&tran_buff[4], reg_array[REGISTER_STAR_REG], reg_array[REGISTER_NUM_REG]);
				tran_buff[tran_buff[3]+4] = xor_create(&tran_buff[1], tran_buff[3]+4);
				//HAL_UART_Transmit_DMA(&huart_slave_it, tran_buff, tran_buff[3]+5);
				HAL_UART_Transmit(&huart_slave_it, tran_buff, tran_buff[3]+5, 1000);
			}
			else
			{
				time_num++;
			}
		}
	}
}

uint8_t receive_data_exam()
{
	if((slave_uart.uart_buff[0] == RECEIVE_HEAD)&&(slave_uart.uart_buff[1] == SLAVE_ADRESS)
		&& slave_uart.uart_buff[slave_uart.uart_buff[3]+4] == xor_create(&slave_uart.uart_buff[1], slave_uart.uart_buff[3]+4))
	{
		return 1;
	}
	else
		return 0;
}

void slave_exam()
{
	//HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
	if(slave_uart.receive_num == slave_uart.buff_num)
	{
		//led_turn();
		//HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
		//HAL_UART_Transmit(&huart_slave_it, slave_uart.uart_buff, 0x09, 1000);
		if(receive_data_exam())
		{
			//HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
			//HAL_UART_Transmit(&huart_slave_it, slave_uart.uart_buff, 0x09, 1000);
			uart_slave_reg_write(&slave_uart.uart_buff[4], slave_uart.uart_buff[2]&0x7F, slave_uart.uart_buff[3]);
			motor_control();
			slave_uart.receive_num = 0;
		}
		else
		{
			//HAL_UART_Transmit_DMA(&huart_slave_it, (uint8_t *)&slave_receive_data, uart_slave_receive_size);
			uart_data_translocate(slave_uart.uart_buff , 0, slave_uart.buff_num);
			slave_uart.receive_num = slave_uart.receive_num - 1;
		}
	}
	HAL_UART_Receive_IT(&huart_slave_it, &slave_uart.uart_bit_buff, 1);
}
